import React, { useState, forwardRef, useImperativeHandle, useMemo, useEffect } from "react"
import { useAppDispatch, useAppSelector } from "~store"
import {
    Button,
    Checkbox,
    Divider,
    Drawer,
    Empty,
    Form,
    Icon,
    ImgDefault,
    Input,
    InputNumber,
    message,
    Modal,
    Popover,
    Progress,
    Radio,
    Select,
    Space,
    Spin,
    Steps,
    Switch,
    Tooltip,
    ImgUpload,
    imgPreview
} from "@bytedance/mona-ui"
import type { UploadFile, UploadChangeParam } from '@bytedance/mona-ui/es/components/img-upload';
import { createTaskId, upImageItemFunc } from "@contents/jinritemaiCopyGoods/copyDataFomate"
import db from "@tools/indexDB";
const { Option } = Select;
const { TextArea } = Input;
const { AddIcon, FinishIcon } = Icon
function ZhutuSetBox(props: any, ref: any) {
    const [showImageKu, setShowImageKu] = useState(false)
    const zhutuImageList: any = useAppSelector(state => state.jinritemaiCopyGoods.zhutuImageList)
    const [selectImages, setSelectImages] = useState<any[]>(zhutuImageList.map((res) => {
        // console.log('边框', res)
        return {
            select: false,
            url: import.meta.env.VITE_PLASMO_PUBLIC_CN_OSS + res
            // url: 'https://wtplug.oss-cn-hangzhou.aliyuncs.com/' + res
        }
    }))
    const infoConfigData = {
        setTypeStatus: 1,
        radioState: '1',
        configType1: [],
        configType1Status: false,
        configType2: [],
        configType2Status: false,
        configType3: {
            type: '1',
            upImageList: []
        },
        configType3Status: false,
        configType4: {
            type: '1',
            upImageList: []
        },
        configType4Status: false,
        configType5: 1,
        configType5Status: false,
        configType6: 1,
        configType6Status: false,
        configType7: 1,
        configType7Status: false,
        configType8: {
            selectBiankuanType: 1,
            huangtuindex: 1,
            selectBiankuanList: []
        },
        configType8Status: false,
    }
    const [getInfoInitDataLodin, setGetInfoInitDataLodin] = useState(false)
    const [setConfigObj, setSetConfigObj] = useState(null)
    useImperativeHandle(ref, () => ({
        setConfigObj
    }))
    useMemo(() => {
        setGetInfoInitDataLodin(true)
        db.copyProductConfig.where('funcname').equals('dly-setConfigObj-zhutu').toArray().then((res) => {
            setGetInfoInitDataLodin(false)
            if (res[0] && res[0].data) {
                setSetConfigObj(res[0].data)
            } else {
                setSetConfigObj(infoConfigData)
            }
        }).catch(err => {
            setGetInfoInitDataLodin(false)
            setSetConfigObj(infoConfigData)
        })
    }, [props])
    useEffect(() => {
        if (setConfigObj) {
            db.copyProductConfig.put({
                funcname: 'dly-setConfigObj-zhutu',
                data: setConfigObj
            })
        }

    }, [setConfigObj])
    function Func1() {
        const plainOptions = [
            { label: '第1张', value: '1' },
            { label: '第2张', value: '2' },
            { label: '第3张', value: '3' },
            { label: '第4张', value: '4' },
            { label: '第5张', value: '5' },
            // { label: '末尾', value: '6' }
        ]

        return <Space direction="vertical">
            <Space>
                {/* <span>AI替换商品主图:</span> */}
                <Checkbox.Group options={plainOptions} defaultValue={setConfigObj.configType1} onChange={(e: any) => {
                    setConfigObj.configType1 = e
                    setSetConfigObj({ ...setConfigObj })
                }} />
            </Space>

        </Space>

    }
    function Func2() {
        const plainOptions = [
            { label: '第1张', value: '1' },
            { label: '第2张', value: '2' },
            { label: '第3张', value: '3' },
            { label: '第4张', value: '4' },
            { label: '第5张', value: '5' },
            // { label: '末尾', value: '6' }
        ]

        return <Space direction="vertical">
            <Space>
                {/* <span>删除主图:</span> */}
                <Checkbox.Group options={plainOptions} defaultValue={setConfigObj.configType2} onChange={(e: any) => {
                    setConfigObj.configType2 = e
                    setSetConfigObj({ ...setConfigObj })
                }} />
            </Space>

        </Space>
    }
    const [addImageLodins3, setAddImageLodins3] = useState(false)
    // const [upImage3, setUpImage3] = useState<any[]>([])
    function Func3() {
        function selectImageEndUpImage() {
            const img = document.createElement('input')
            img.type = 'file'
            img.multiple = true
            img.accept = 'image/*'
            img.onchange = (e: any) => {
                const files = e.target.files
                setAddImageLodins3(true)
                let addIndex = 0

                for (let i = 0; i < files.length; i++) {
                    const reader = new FileReader();
                    reader.readAsDataURL(files[i]);
                    reader.onload = function (e) {
                        const base64: any = e.target.result;

                        const img = new Image();
                        img.src = base64;
                        img.onload = function () {
                            const width = img.width;
                            const height = img.height;
                            if (width !== height) {
                                message.error('请上传1:1的图片');
                                setAddImageLodins3(false)
                                return;
                            }
                            if (width < 600) {
                                message.error('请上传大于600*600的图片');
                                setAddImageLodins(false)
                                return;
                            }
                            const upImageId = createTaskId()
                            addIndex++
                            if (addIndex >= files.length) {
                                setAddImageLodins3(false)
                            }
                            const setImageDatas = {
                                uid: upImageId,
                                base64: base64,
                                statusStr: 'uploding',
                                url: ''
                            }
                            setConfigObj.configType3.upImageList.push(setImageDatas)
                            // setUpImage3([...upImage3])
                            upImageItemFunc(base64).then(res => {
                                const setimageUpstatus: any = setConfigObj.configType3.upImageList.find(item => item.uid === upImageId)
                                setimageUpstatus.statusStr = 'upend'
                                setimageUpstatus.url = res.data[0]
                                // setConfigObj.configType3.upImageList = upImage3
                                // setUpImage3([...upImage3])
                                setSetConfigObj({ ...setConfigObj })
                            })
                        }

                    }
                }
            }
            img.click()
        }
        return <Spin spinning={addImageLodins3}>
            <Space align="start">
                {/* <span>添加主图:</span> */}
                <Space direction="vertical">
                    <Space wrap>
                        {setConfigObj.configType3.upImageList.map((item, idnex) => {
                            return <Spin spinning={item.statusStr === 'uploding'} key={idnex}>
                                <Popover content={(<Space className="seghetewe">
                                    <Icon type="SeeIcon" className="njndhgr" onClick={() => {
                                        imgPreview({
                                            defaultIndex: idnex,
                                            imgUrl: setConfigObj.configType3.upImageList.map((item: any) => item.url),
                                        });
                                    }}></Icon>
                                    <Icon type="DeleteIcon" className="njndhgr" onClick={() => {
                                        // const delImage = upImage3.filter((itemser: any) => item.uid !== itemser.uid)
                                        setConfigObj.configType3.upImageList = setConfigObj.configType3.upImageList.filter((itemser: any) => item.uid !== itemser.uid)
                                        // setUpImage3(delImage)
                                        setSetConfigObj({ ...setConfigObj })
                                    }}></Icon>
                                </Space>)}>
                                    <img src={item.statusStr === 'uploding' ? item.base64 : item.url} key={idnex} style={{
                                        width: 90,
                                        height: 90,
                                        objectFit: 'cover',
                                        borderRadius: 5,
                                    }}></img>
                                </Popover>

                            </Spin>
                        })}
                        <div className="upImageBox98798" onClick={selectImageEndUpImage}>
                            <Space direction="vertical" align="center" className="njherssd">
                                <span className="miher">+</span>
                                <span className="jiner">点击上传图片</span>
                            </Space>
                        </div>
                        {!!setConfigObj.configType3.upImageList.length && <Button type="primary" size="small" onClick={() => {
                            setConfigObj.configType3.upImageList = []
                            setSetConfigObj({ ...setConfigObj })
                        }}>删除全部</Button>}
                    </Space>
                    <Space>
                        <span>插入位置:</span>
                        <Select style={{
                            width: 130
                        }} defaultValue={setConfigObj.configType3.type}
                            size="small"
                            onChange={(e: any) => {
                                setConfigObj.configType3.type = e
                                setSetConfigObj({ ...setConfigObj })
                            }}>
                            <Option value="1">第1张主图前</Option>
                            <Option value="2">第2张主图前</Option>
                            <Option value="3">第3张主图前</Option>
                            <Option value="4">第4张主图前</Option>
                            <Option value="5">第5张主图前</Option>
                            <Option value="6">追加到末尾</Option>
                        </Select>
                    </Space>
                </Space>

            </Space>
        </Spin>
    }
    // const [upImage4, setUpImage4] = useState([])
    const [addImageLodins, setAddImageLodins] = useState(false)
    function Func4() {
        function selectImageEndUpImage() {
            const img = document.createElement('input')
            img.type = 'file'
            img.multiple = true
            img.accept = 'image/*'
            img.onchange = (e: any) => {
                const files = e.target.files
                setAddImageLodins(true)
                let addIndex = 0

                for (let i = 0; i < files.length; i++) {
                    const reader = new FileReader();
                    reader.readAsDataURL(files[i]);
                    reader.onload = function (e) {

                        // 过滤不是1:1的图片
                        const base64: any = e.target.result;

                        const img = new Image();
                        img.src = base64;
                        img.onload = function () {
                            const width = img.width;
                            const height = img.height;
                            if (width !== height) {
                                message.error('请上传1:1的图片');
                                setAddImageLodins(false)
                                return;
                            }
                            if (width < 600) {
                                message.error('请上传大于600*600的图片');
                                setAddImageLodins(false)
                                return;
                            }
                            const upImageId = createTaskId()
                            addIndex++
                            if (addIndex >= files.length) {
                                setAddImageLodins(false)
                            }
                            const setImageDatas = {
                                uid: upImageId,
                                base64: base64,
                                statusStr: 'uploding',
                                url: ''
                            }
                            setConfigObj.configType4.upImageList.push(setImageDatas)
                            // setUpImage4([...upImage4])
                            upImageItemFunc(base64).then(res => {
                                const setimageUpstatus: any = setConfigObj.configType4.upImageList.find(item => item.uid === upImageId)
                                setimageUpstatus.statusStr = 'upend'
                                setimageUpstatus.url = res.data[0]
                                // setConfigObj.configType4.upImageList = upImage4
                                // setUpImage4([...upImage4])
                                setSetConfigObj({ ...setConfigObj })
                            })
                        }

                    }
                }
            }
            img.click()
        }
        return <Spin spinning={addImageLodins}>
            <Space align="start">
                <Space direction="vertical">
                    <Space wrap>
                        {setConfigObj.configType4.upImageList.map((item, idnex) => {
                            return <Spin spinning={item.statusStr === 'uploding'} key={idnex}>
                                <Popover content={(<Space className="seghetewe">
                                    <Icon type="SeeIcon" className="njndhgr" onClick={() => {
                                        imgPreview({
                                            defaultIndex: idnex,
                                            imgUrl: setConfigObj.configType4.upImageList.map((item: any) => item.url),
                                        });
                                    }}></Icon>
                                    <Icon type="DeleteIcon" className="njndhgr" onClick={() => {
                                        // const delImage = upImage4.filter((itemser: any) => item.uid !== itemser.uid)
                                        setConfigObj.configType4.upImageList = setConfigObj.configType4.upImageList.filter((itemser: any) => item.uid !== itemser.uid)
                                        // setUpImage4(delImage)
                                        setSetConfigObj({ ...setConfigObj })
                                    }}></Icon>
                                </Space>)}>
                                    <img src={item.statusStr === 'uploding' ? item.base64 : item.url} key={idnex} style={{
                                        width: 90,
                                        height: 90,
                                        objectFit: 'cover',
                                        borderRadius: 5,
                                    }}></img>
                                </Popover>

                            </Spin>
                        })}
                        <div className="upImageBox98798" onClick={selectImageEndUpImage}>
                            <Space direction="vertical" align="center" className="njherssd">
                                <span className="miher">+</span>
                                <span className="jiner">点击上传图片</span>
                            </Space>
                        </div>
                        {!!setConfigObj.configType4.upImageList.length && <Button type="primary" size="small" onClick={() => {
                            setConfigObj.configType4.upImageList = []
                            setSetConfigObj({ ...setConfigObj })
                        }}>删除全部</Button>}
                    </Space>

                    <Space>
                        <span>插入位置:</span>
                        <Select style={{
                            width: 130
                        }} defaultValue={setConfigObj.configType4.type}
                            size="small"
                            onChange={(e: any) => {
                                setConfigObj.configType4.type = e
                                setSetConfigObj({ ...setConfigObj })
                            }}>
                            <Option value="1">替换第1张主图</Option>
                            <Option value="2">替换第2张主图</Option>
                            <Option value="3">替换第3张主图</Option>
                            <Option value="4">替换第4张主图</Option>
                            <Option value="5">替换第5张主图</Option>
                            <Option value="6">替换到末尾</Option>
                        </Select>
                    </Space>
                </Space>

            </Space>
        </Spin>
    }
    function Func5() {

        return <Space align="start">
            {/* <span>将当前首图移到第:</span> */}
            <InputNumber size="small" defaultValue={setConfigObj.configType5} min={1} max={5} onBlur={(e: any) => {
                setConfigObj.configType5 = e.target.value
                setSetConfigObj({ ...setConfigObj })
            }}></InputNumber>
            <span >位</span>
            <span style={{
                color: '#9d9d9d',
                fontSize: 12

            }}>(若设置位数超过图片数量则移到最后)</span>
        </Space>
    }
    function Func6() {
        return <Space align="start">
            {/* <span>将第:</span> */}
            <InputNumber size="small" defaultValue={setConfigObj.configType6} min={1} max={5} onBlur={(e: any) => {
                setConfigObj.configType6 = e.target.value
                setSetConfigObj({ ...setConfigObj })
            }}></InputNumber>
            <span > 张主图设为首图</span>
            <span style={{
                color: '#9d9d9d',
                fontSize: 12
            }}>(若设置位数超过图片数量则将最后一张主图设为首图)</span>
        </Space>
    }
    function Func7() {
        return <Space>
            <span>随机打乱:</span>
            <Radio.Group value={setConfigObj.configType7} onChange={(e: any) => {
                setConfigObj.configType7 = e.target.value
                setSetConfigObj({ ...setConfigObj })
            }}>
                <Radio value={1}>首图不变位置  </Radio>
                <Radio value={2}>首图改变位置</Radio>

            </Radio.Group>
        </Space>
    }

    function Func8() {

        return <Space direction="vertical" >

            <Space>
                <Button type="primary" size="mini" onClick={() => {
                    setShowImageKu(true)
                }} icon={<Icon type="GalleryIcon"></Icon>}>边框库</Button>
                <Select size="small" value={setConfigObj.configType8.huangtuindex} style={{
                    width: 150
                }} onChange={(e: any) => {
                    setConfigObj.configType8.huangtuindex = e
                    setSetConfigObj({ ...setConfigObj })
                }}>
                    <Option value={1}>换第1张主图</Option>
                    <Option value={2}>换第2张主图</Option>
                    <Option value={3}>换第3张主图</Option>
                    <Option value={4}>换第4张主图</Option>
                    <Option value={5}>换第5张主图</Option>
                    <Option value={6}>换全部主图</Option>
                </Select>
                <Radio.Group value={setConfigObj.configType8.selectBiankuanType} onChange={(e) => {
                    setConfigObj.configType8.selectBiankuanType = e.target.value
                    setSetConfigObj({ ...setConfigObj })
                }}>
                    <Radio value={1}>随机选择边框</Radio>
                    <Radio value={2}>按顺序选择边框</Radio>
                </Radio.Group>
            </Space>
            <Space wrap >
                {setConfigObj.configType8.selectBiankuanList.map((item, index) => {
                    return <Popover key={index} content={(<ImgDefault imgSrc={item.url} width={100} height={100} ></ImgDefault>)} placement="top" title={item.name} trigger="hover">
                        <img src={item.url} style={{
                            width: 40,
                            height: 40
                        }} />
                    </Popover>

                })}
            </Space>
        </Space>

    }

    if (!setConfigObj) return <div className="ciner" style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    }}>
        <Spin></Spin>
    </div>

    return <>
        <Spin spinning={getInfoInitDataLodin}>


            <Space direction="vertical">
                <h4>主图</h4>
                <Radio.Group value={setConfigObj.setTypeStatus} onChange={(e) => {
                    setConfigObj.setTypeStatus = e.target.value
                    setSetConfigObj({ ...setConfigObj })
                }}>
                    <Radio value={1}>单独设置</Radio>
                    <Space size={0}>
                        <Radio value={2}>混合设置</Radio>
                        <span style={{
                            fontSize: 12,
                            color: '#999'
                        }}>(根据裂变数量随机使用选中并设置的项进行设置)</span>
                    </Space>
                </Radio.Group>
                {setConfigObj.setTypeStatus === 1 && <Radio.Group value={setConfigObj.radioState} onChange={(e) => {
                    setConfigObj.radioState = e.target.value
                    setSetConfigObj({ ...setConfigObj })
                }}>
                    <Space direction="vertical">
                        <Space align="start" size={4}><Radio value={'1'} >AI替换商品主图:</Radio> <Func1 /></Space>
                        <Space align="start" size={4}><Radio value={'2'} >删除主图:</Radio> <Func2 /></Space>
                        <Space align="start" size={4}><Radio value={'3'} style={{
                            width: 98
                        }}>添加主图:</Radio> <Func3 /></Space>
                        <Space align="start" size={4}><Radio value={'4'} style={{
                            width: 98
                        }}>主图替换:</Radio> <Func4 /></Space>
                        <Space align="center" size={4}><Radio value={'5'} >将当前首图移到第:</Radio> <Func5 /></Space>
                        <Space align="center" size={4}><Radio value={'6'} >将第:</Radio> <Func6 /></Space>
                        <Space align="center" size={4}><Radio value={'7'} >随机打乱:</Radio> <Func7 /></Space>
                        <Space align="start" size={4}><Radio value={'8'} style={{
                            width: 98
                        }} >使用边框:</Radio> <Func8 /></Space>

                    </Space>
                </Radio.Group>}
                {setConfigObj.setTypeStatus === 2 && <Space direction="vertical" align="start">
                    <Space align="start">
                        <Checkbox checked={setConfigObj.configType1Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType1Status: e.target.checked })
                        }}>AI替换商品主图:</Checkbox> <Func1 />
                    </Space>
                    <Space align="start">
                        <Checkbox checked={setConfigObj.configType2Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType2Status: e.target.checked })
                        }}  >删除主图:</Checkbox> <Func2 />
                    </Space>
                    <Space align="start">
                        <Checkbox checked={setConfigObj.configType3Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType3Status: e.target.checked })
                        }} style={{
                            width: 98
                        }}>添加主图:</Checkbox> <Func3 />
                    </Space>
                    <Space align="start">
                        <Checkbox checked={setConfigObj.configType4Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType4Status: e.target.checked })
                        }} style={{
                            width: 98
                        }}>主图替换:</Checkbox> <Func4 /></Space>
                    <Space align="center">
                        <Checkbox checked={setConfigObj.configType5Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType5Status: e.target.checked })
                        }}  >将当前首图移到第:</Checkbox> <Func5 /></Space>
                    <Space align="center">
                        <Checkbox checked={setConfigObj.configType6Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType6Status: e.target.checked })
                        }} >将第:</Checkbox> <Func6 /></Space>
                    <Space align="center">
                        <Checkbox checked={setConfigObj.configType7Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType7Status: e.target.checked })
                        }}  >随机打乱:</Checkbox> <Func7 /></Space>
                    <Space align="start">
                        <Checkbox checked={setConfigObj.configType8Status} onChange={(e) => {
                            setSetConfigObj({ ...setConfigObj, configType8Status: e.target.checked })
                        }} style={{
                            width: 98
                        }} >使用边框:</Checkbox>  <Func8 /></Space>
                </Space>}
            </Space>
        </Spin>
        <Modal
            width={650}
            visible={showImageKu}
            title={`选择边框 ${selectImages.filter((item) => item.select).length}`}
            okText=" 确定"
            cancelText=" 取消"
            onCancel={() => setShowImageKu(false)}
            onOk={() => {
                setConfigObj.configType8.selectBiankuanList = selectImages.filter((item) => item.select)
                setSetConfigObj({ ...setConfigObj })
                setShowImageKu(false)
            }}
        >

            <div className="selectListerimgae">
                {selectImages.map((res: any, index: number) => {
                    return (
                        <div className="contr" key={index}>
                            <img
                                className="imageconer"
                                src={res.url}
                                alt={res.url}
                                onClick={() => {
                                    res.select = !res.select
                                    setSelectImages([...selectImages])
                                }}
                            />
                            {res.select && <FinishIcon className="selectImage" />}
                        </div>
                    )
                })}
            </div>


        </Modal>
    </>
}
export default forwardRef(ZhutuSetBox)